import re
from collections import OrderedDict
from django.conf import settings
from django.urls import URLPattern
from django.urls import URLResolver
from django.urls.resolvers import RegexPattern
from django.urls.resolvers import RoutePattern
from django.utils.module_loading import import_module


def check_url_exclude(url):
    """

    :param url:
    :return:
    """
    for regex in settings.AUTO_DISCOVER_EXCLUDE_URL:
        if re.match(regex, url):
            return True


def recursion_url(pre_namespace, pre_url, url_patterns, url_ordered_dict):
    """
    自动递归发现项目中的所有URL
    :param pre_namespace:
    :param pre_url:
    :param url_patterns:
    :param ordered_dict:
    :return:
    """
    for item in url_patterns:
        if isinstance(item, URLPattern):
            if not item.name:
                continue
            name = item.name
            if pre_namespace:
                name = '%s:%s' % (pre_namespace, name)
            if isinstance(item.pattern, RegexPattern):
                url = pre_url + item.pattern._regex
            elif isinstance(item.pattern, RoutePattern):
                url = pre_url + item.pattern._route

            url = url.replace('^', '').replace('$', '')
            if check_url_exclude(url):
                continue
            url_ordered_dict[name] = {
                'name': name,
                'url': url
            }
        elif isinstance(item, URLResolver):
            if pre_namespace:
                if item.namespace:
                    namespace = '%s:%s' % (pre_namespace, item.namespace)
                else:
                    namespace = item.namespace
            else:
                if item.namespace:
                    namespace = item.namespace
                else:
                    namespace = None
            if isinstance(item.pattern, RoutePattern):
                url = pre_url + item.pattern._route
            elif isinstance(item.pattern, RegexPattern):
                url = pre_url + item.pattern._regex
            recursion_url(namespace, url, item.url_patterns, url_ordered_dict)


def get_all_url_dict():
    """
    获取项目中的所有Url
    :return:
    """
    url_ordered_dict = OrderedDict()

    md = import_module(settings.ROOT_URLCONF)
    recursion_url(None, '/', md.urlpatterns, url_ordered_dict)
    return url_ordered_dict
